<?php

namespace july\julyadmin\builder\forms;

use july\julyadmin\builder\FormBase;

/**
 * 表单tabs组件
 */
class Tabs extends FormBase
{
    public $tabs = [];
    /**
     * 添加组件
     * @Author
     * @DateTime 2023-07-16T12:14:26+0800
     * @param    string                   $tab_id 选项卡id
     * @return this
     */
    public function __construct($tab_id = '')
    {
        $form         = new \stdClass();
        $form->type   = 'tabs';
        $form->tab_id = $tab_id;
        $form->label  = '';
        $form->active = false;
        $this->form   = $form;
        return $this;
    }

    /**
     * 添加tab
     * @Author
     * @DateTime 2023-07-16T12:40:13+0800
     * @param    string                   $label  tab名称
     * @param    string                   $tab_id tabid
     * @param    boolean                  $active 是否选中
     */
    public function addTab($label = '', $tab_id = '', $active = true)
    {
        if (!$label) {
            throw new \Exception("tab名称label不能为空！");
        }

        if (!$tab_id) {
            throw new \Exception("tab ID不能为空！");
        }

        foreach ($this->tabs as $tab_k => $tab_v) {
            if ($tab_v->tab_id == $tab_id) {
                throw new \Exception("tab ID不能重复！");
            }
        }

        $tab          = new \stdClass();
        $tab->label   = $label;
        $tab->tab_id  = $tab_id;
        $tab->active  = $active;
        $this->tabs[] = $tab;
        return $this;
    }

    /**
     * 渲染组件
     * @Author
     * @DateTime 2023-07-16T12:21:53+0800
     * @return   array
     */
    public function render()
    {
        $this->html .= <<< EOT

                <ul class="nav nav-tabs nav-tabs-{$this->form->tab_id}" role="tablist">
EOT;
        foreach ($this->tabs as $tab_k => $tab_v) {
            $active = $tab_v->active ? ' active' : '';
            $this->html .= <<<EOT

                    <li class="nav-item">
                        <a class="nav-link{$active}" href="#tabs_{$tab_v->tab_id}" data-bs-toggle="tab">{$tab_v->label}</a>
                    </li>
EOT;

        }
        $this->html .= <<<EOT

                </ul>
EOT;

        foreach ($this->tabs as $tab_k => $tab_v) {
            if ($tab_v->active) {
                $this->script .= <<<EOT

                <script>
                    $('#tabs_{$tab_v->tab_id}').addClass('active show');
                    //这个代码必须要有，不然切换tabs会发现webuploader插件点击没反应
                    $('.nav-item').click(function(){
                        setTimeout(function(){
                            $(window).resize();
                        },500);
                    });
                    setTimeout(function(){
                        $(window).resize();
                    },500);
                </script>

EOT;
            }
        }

        $result = ['html' => $this->html, 'script' => $this->script];
        return $result;
    }
}
